<?php
/**
 * Created by PhpStorm.
 * User: 12707
 * Date: 2019/4/17
 * Time: 21:50
 */

namespace App\Utils;


use App\Model\Order\MealSupplementBalance;
use Exception;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;

class TeacherRechargeUnit
{
    public static function recharge($order_price, $id)
    {
        try {
            $order_price = abs($order_price);
            $uuid3 = Uuid::uuid1();
            $str = $uuid3->getHex();
            $meal = MealSupplementBalance::find($id);
            $history_meal_supplement_balance = $meal->meal_supplement_balance + $order_price;
            DB::transaction(function () use ($meal, $order_price, $str, $history_meal_supplement_balance) {
                $meal->meal_supplement_balance = $history_meal_supplement_balance;
                $meal->userOrder()->create([
                    "order_price" => $order_price,
                    "history_meal_supplement_balance" => $history_meal_supplement_balance,
                    "uid" => $str,
                    'isRecharge' => 1
                ]);
                $meal->save();
            }, 5);
            return ['code' => 200, 'data' => $order_price];
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public static function deduction($order_price, $id)
    {
        try {
            $order_price = abs($order_price);
            $uuid3 = Uuid::uuid1();
            $str = $uuid3->getHex();
            $meal = MealSupplementBalance::find($id);
            $history_meal_supplement_balance = $meal->meal_supplement_balance - $order_price;
            if ($history_meal_supplement_balance < 0) {
                return ['code' => 403, 'data' => '余额不足'];
            }
            DB::transaction(function () use ($meal, $order_price, $str, $history_meal_supplement_balance) {
                $meal->meal_supplement_balance = $history_meal_supplement_balance;
                $meal->userOrder()->create([
                    "order_price" => -$order_price,
                    "history_meal_supplement_balance" => $history_meal_supplement_balance,
                    "uid" => $str,
                    'isRecharge' => 0
                ]);
                $meal->save();
            }, 5);
            return ['code' => 200, 'data' => $history_meal_supplement_balance];
        } catch (Exception $e) {
            return ['code' => 500, 'data' => $e->getMessage()];
        }
    }
}
